package com.hzj.rtsp.controller;

import com.hzj.rtsp.service.AdminService;
import com.hzj.rtsp.dto.Video;
import com.hzj.rtsp.service.IFLVService;
import com.hzj.rtsp.task.TaskMaager;
import com.hzj.rtsp.task.VideoUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by Hzj on 2021-1-27.
 */
@RestController
public class PullController {

    @Value("${filepath.m3u8path}")
    private String m3u8path;


    @Autowired
    private IFLVService service;


    @Autowired
    private AdminService adminService;

    //无需nginx推流服务器，本身服务器够强就行，切可以集群部署
    @GetMapping(value = "/hls/{videoid}/index.m3u8")
    public void hlsPlay(@PathVariable(value = "videoid") String videoid,
                          HttpServletResponse response,
                           HttpServletRequest request) throws Exception{

      TaskMaager.createTask(videoid,m3u8path);
      boolean isfile =false;
      for(int i=0;i<40;i++){
           isfile = renderFile(videoid,response);
            if(isfile)
            {
                break;
            }
            else
            {
                //20秒内m3u8文件还没生成就返回失败
                Thread.sleep(500);
            }
      }
      if(!isfile) {
          response.sendError(HttpServletResponse.SC_NOT_FOUND);
      }
        //return R.ok();
    }
    @GetMapping(value = "/hls/{videoid}/index{index}.ts")
    public void hlsPlayTS(@PathVariable(value = "videoid") String videoid,
                          @PathVariable(value = "index") Integer index,
                        HttpServletResponse response) throws Exception{
       // index++;//第一个文件不取，因为经常会出现错误，无法播放
        String m3u8FilePath = m3u8path+"/"+videoid+"/index"+index+".ts";
        File file = new File(m3u8FilePath);

        if(file.exists()) {
            response.setContentType("application/x-linguist");
            OutputStream output = response.getOutputStream();
            InputStream inputStream = new FileInputStream(file);
            IOUtils.copy(inputStream, output);
            try {
                inputStream.close();
                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 public boolean renderFile(String  videoid,HttpServletResponse response)throws Exception{
     String m3u8FilePath = m3u8path+"/"+videoid+"/index.m3u8";
     File file = new File(m3u8FilePath);
     if(file.exists()){
         response.setContentType("audio/x-mpegur");
         OutputStream output  = response.getOutputStream();
         InputStream inputStream = new FileInputStream(file);
         IOUtils.copy(inputStream,output);
         try {
             inputStream.close();
             output.flush();
         } catch (IOException e) {
             e.printStackTrace();
         }
         return true;
     }
     return false;
 }

        //无需nginx推流服务器，本身服务器够强就行，切可以集群部署
    @GetMapping(value = "/video/{videoid}/live.flv",produces = {"video/x-flv;charset=UTF-8"})
    public void pullVideo(@PathVariable(value = "videoid") String videoid, HttpServletResponse response,
                            HttpServletRequest request) {
        Video video = adminService.getVideoById(videoid);
        String url= VideoUtil.getRTSPUrl(video);
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        if(!StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)){
            //回放
            url= VideoUtil.getRTSPPlayBackUrl(video);
            starttime=starttime.replaceAll("-","");
            endtime=endtime.replaceAll("-","");
            url+="?starttime="+starttime+"&endtime="+endtime;
        }

        //非网关时开启这里，flvjs差劲播放
       // response.setHeader("Access-Control-Allow-Origin", "*");//走网关时去掉这行
        service.open(url,videoid, response, request);
    }


}